﻿using EasyNetQ;
using EasyNetQTest.AspnetCore.Config;
using EasyNetQTest.AspnetCore.Models;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;


namespace EasyNetQTest.AspnetCore.Services
{
    /// <summary>
    /// 后台运行的任务
    /// 消息消费者，多个消费者
    /// </summary>
    public class MQMultiRevieveService : IHostedService, IDisposable
    {
        //List<IBus> busList = new List<IBus>();

        IServiceProvider serviceProvider;
        IBus bus;

        public MQMultiRevieveService(IServiceProvider serviceProvider, IBus bus)
        {
            this.serviceProvider = serviceProvider;
            this.bus = bus;
        }

 
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            int pocCount = 10;
            //bus = serviceProvider.GetService<IBus>();
            //创建10个消息费者来同时处理消息
            for (int i = 0; i < pocCount; i++)
            {
                //连接MQ
                //IBus bus = RabbitHutch.CreateBus(connStr);
                
                //busList.Add(bus);

                await doWorkAsync(bus,"消费者" +  i.ToString());
            }
        }

        /// <summary>
        /// 消息处理方法
        /// </summary>
        /// <param name="bus"></param>
        /// <param name="busName"></param>
        public async Task doWorkAsync(IBus bus, string busName)
        {
            await Task.Run(() =>
            {
                //直接从队列中接收消息
                bus.Receive<MQMessage>(Consts.QueueName, o =>
                 {
                     Console.WriteLine(busName + ",收到消息: {0}", o.MsgContent);

                     Thread.Sleep(500);//模拟耗时,进行消息处理                        
                     Console.WriteLine(busName + $",{o.MsgId}处理结束\n");
                 });
             });
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            //服务结束时，Dispose
            //busList.ForEach(o => o.Dispose());
            bus.Dispose();
            return Task.CompletedTask;
        }

        public void Dispose()
        {

        }
    }
}
